angular.module('starter.controllers', [])

.controller('AppCtrl', function($scope, $ionicModal, $timeout, $ionicPopup, $translate, $filter, APP) {
  // Form data for the login modal
  $scope.loginData = {};

  $scope.tlData = {
    staticValue : 42,
    randomValue : Math.floor(Math.random() * 1000)
  };

  $scope.jsTrSimple = $translate.instant('SERVICE');
  $scope.jsTrParams = $translate.instant('SERVICE_PARAMS', $scope.tlData);

  $scope.setLang = function(langKey) {
    // You can change the language during runtime
    $translate.use(langKey);

    // A data generated by the script have to be regenerated
    $scope.jsTrSimple = $translate.instant('SERVICE');
    $scope.jsTrParams = $translate.instant('SERVICE_PARAMS', $scope.tlData);
  };  
  
  // Create the login modal that we will use later
  $ionicModal.fromTemplateUrl('templates/login.html', {
    scope: $scope
  }).then(function(modal) {
		$scope.modal = modal;
		$scope.login();
  });

  // Triggered in the login modal to close it
  $scope.closeLogin = function() {
    //$scope.modal.hide();
	navigator.app.exitApp();
  };

  // Open the login modal
	$scope.login = function() {
		/*var data = JSON.parse(localStorage.getItem("person"));
		
		//console.log(JSON.stringify(data));
		if( (data !== null) && (data[0]['message'] == 'success')){
			$scope.user_id = data[0]['user_id'];
			APP.user_id = data[0]['user_id'];
		}*/
		if( APP.user_id == 0){
			$scope.modal.show();
		}
		else
		{
			$scope.user_id = APP.user_id;
		}
	};

  // Perform the login action when the user submits the login form
	$scope.doLogin = function() {
		//console.log('Doing login', $scope.loginData);

		//var my_url = "http://alturarunning.bugs3.com/webservice.php";
	   var my_url = "http://alturarunning.zz.mu/webservice.php";
		var item = {};
		var username = $scope.loginData["username"];
		var password = $scope.loginData["password"];
		item.user_name= username;
		item.function = 'getUserByUsername';
					
		$.ajaxSetup({
			beforeSend: function(xhr) {
				xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
			}
		});

		$.ajax({
			url: my_url,
			type: 'POST',
			data: item,
			contentType: "application/json; charset=utf-8",
			dataType: "jsonp",
			jsonp: "callback",
			jsonpCallback: "localJsonpCallback",
			success: function (data) {
				//console.log(JSON.stringify(data));
				
				var result1, result2, message;

				for(var i = 0; i < data.length; i++)
				{
					//app.user_id = data[i].user_id;
					user_pass = data[i].user_pass;
					message = data[i].message;
					
					//console.log(JSON.stringify(data));
					// Do something with result and result2, or message.
					window.localStorage.setItem("person",JSON.stringify(data));

					if( user_pass === password	){
						$scope.user_id = data[0]['user_id'];
						$scope.modal.hide();
						
					}
					else
						APP.showAlert("invalid_username_password");
				}
						
			},
			error: function (xhr, ajaxOptions, thrownError) {
			   console.log('on error!');
			   console.log("xhr.status: " + xhr.status);
			   console.log("xhr.statusText: " + xhr.statusText);
			   console.log("xhr.readyState: " + xhr.readyState);
			   console.log("xhr.redirect: " + xhr.redirect);
			   return false;
			}
		});
		/*$timeout(function() {
			$scope.closeLogin();
		}, 1000);*/
	};
	
	$scope.logout= function(){
		var confirmPopup = $ionicPopup.confirm({
			title: 'Altura running',
			template: $filter('translate')('sure_logout')
		});
	   
		confirmPopup.then(function(res) {
			if(res) {
				if( localStorage.getItem("exercise_id") != 0)
				{
					localStorage.removeItem("person");
				
					$location.path('/app/exercises');
				}
			} else {
				//console.log('You are not sure');
			}
		});	
	}
	
	localJsonpCallback= function(json) {

	};	


})


.controller('ExercisesCtrl', function($scope, ExerciseService, APP){
   $scope.exercises = [];
    $scope.exercise = null;
	
    // Get all the exercises
    ExerciseService.all().then(function(exercises){
        $scope.exercises = exercises;
    });
})


.controller('ExerciseDetailCtrl', function($scope, $location, $stateParams,  $timeout, $ionicPopup, $filter, ExerciseService, 
										   StatisticsService, ExerciseDetailsService, APP){
   //$scope.exercises = [];
    //$scope.exercise = null;
	
	//console.log($stateParams.id);
    // Get one document, example with id = 2
    
	ExerciseService.getById($stateParams.id).then(function(exercise) {
        $scope.exercise = exercise;
		localStorage.setItem("exercise_id",exercise.id);
    });
	
	StatisticsService.getByExerciseId($stateParams.id).then(function(statistics){
		$scope.statistics = statistics;
	});
	
	//Temp
	/*ExerciseDetailsService.count($stateParams.id).then(function(total){
		$scope.total = total;
	});*/
	
	$scope.upload = function(){
	
		var confirmPopup = $ionicPopup.confirm({
			title: 'Altura running',
			template: $filter('translate')('sure_upload')
		});
	   
		confirmPopup.then(function(res) {
			if(res) {
				if( localStorage.getItem("exercise_id") != 0)
				{
					ExerciseService.getById(localStorage.getItem("exercise_id"), true).then(function(exercise) {
						$scope.exercise = exercise;
					});	
					
					
					StatisticsService.getByExerciseId(localStorage.getItem("exercise_id"), true).then(function(statistics){
						$scope.statistics = statistics;
					});

					ExerciseDetailsService.getByExerciseId(localStorage.getItem("exercise_id"), true).then(function(details){
						$scope.details = details;
					});
					
					$timeout(function() {
						ExerciseService._export($scope.exercise, $scope.details, $scope.statistics);
					}, 1000);
				}
			} else {
				//console.log('You are not sure');
			}
		});	
		
		//APP.showAlert("Exercise uploaded with success!");
	};
	
	$scope.showExerciseOptions = function(){
		$location.path('/app/exercise_options');
	}
	
	$scope.deleteExercise= function(){
		var confirmPopup = $ionicPopup.confirm({
			title: 'Altura running',
			template: $filter('translate')('sure_delete')
		});
	   
		confirmPopup.then(function(res) {
			if(res) {
				if( localStorage.getItem("exercise_id") != 0)
				{
					//console.log(localStorage.getItem("exercise_id"));
					ExerciseService.deleteExercise(localStorage.getItem("exercise_id"));
					localStorage.setItem("exercise_id", 0);
					APP.showAlert("deleted_exercise");
					$location.path('/app/exercises');
				}
			} else {
				//console.log('You are not sure');
			}
		});		
	}
})


.controller('NewExerciseCtrl', function($scope, ExerciseService){
	
	//ExerciseService.render();
	
	$scope.start = function() {
		ExerciseService.start();
	}
		
	$scope.stop= function(){
		ExerciseService.stop();
	}
})


.controller('PreExerciseCtrl', function($scope, $location, $filter, $ionicModal, ExerciseService, APP){
	var timer;
   var useHrm = JSON.parse(localStorage.getItem("useHrm"));
   
   
   $scope.useHrm = useHrm == null ? false : useHrm;
  
	// Create the login modal that we will use later
	$ionicModal.fromTemplateUrl('templates/modal.html', {
		scope: $scope
		}).then(function(modal) {
			$scope.modal = modal;
	});	
	
	$scope.searchGps = function() {
      if( ExerciseService.isStarted()){
         $location.path('/app/new_exercise');	
      }
      else{
         $scope.modal.show();
         if( $scope.useHrm )
            ExerciseService.searchHeartRate();
            
         if( ! ExerciseService.isSearchingGps()){
            ExerciseService.searchGps();
            timer = setInterval(function (){verify()}, 1000);
         }
      }
	}
	
	$scope.stopSearch= function(){
		ExerciseService.stopSearchGps();
	}
	
	$scope.cancel= function(){
		clearInterval(timer);
		ExerciseService.stopSearchGps();
		$scope.modal.hide();		
		$location.path('/app/resume');
	}
	
	$scope.showWhileExercise= function(){
		$location.path('/app/while_exercise');
	}
	
   $scope.onChangeHrm= function(){
      window.localStorage.setItem("useHrm",$scope.useHrm);
   }
   
   
   
	verify= function(){
		$('#accuracy').html(ExerciseService.getAccuracy());
		if(!ExerciseService.isSearchingGps()){
			clearInterval(timer);
			$scope.modal.hide();
			goNewExercise();
		}
	}

	goNewExercise= function(){
		var config = JSON.parse(localStorage.getItem("config"));
		if( config === null){
			config = {};
		}
		var name = $('#txt_name').val();
		if (name == "")
			name= $filter('translate')('run');
		
		config.exercise_name = name;
		config.exerciseType = $('#slt_type').val();
		config.isIndoor = false;
		
		window.localStorage.setItem("config",JSON.stringify(config));
		ExerciseService.render();
		$location.path('/app/new_exercise');	
	}
		
})


.controller('ResumeCtrl', function($scope, ResumeService){
	localStorage.removeItem('config');
	
	ResumeService.getLastExercise().then(function(exercise){
		$scope.exercise = exercise;
	});
	
	ResumeService.getLastWeek().then(function(last_week){
		$scope.last_week = last_week;
	});
	
	ResumeService.getLastMonth().then(function(last_month){
		$scope.last_month = last_month;
	});
})


.controller('WhileExerciseCtrl', function($scope){

})


.controller('ConfigurationCtrl', function($scope, $translate){
  $scope.items = [
    { id: 'en_US', name: 'english'},
    { id: 'pt_BR', name: 'portuguese' }];
	
  $scope.changeLanguage = function (key) {
    $translate.use(key);
	
    // A data generated by the script have to be regenerated
    //$scope.jsTrSimple = $translate.instant('SERVICE');
    //$scope.jsTrParams = $translate.instant('SERVICE_PARAMS', $scope.tlData);	
	//$translate.rememberLanguage(true);
  };
});